package com.runa.monitor.platinterface.meter3_0.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author diandian
 * @Date 2022/11/8 10:49
 */
@Slf4j
public class MySqlJdbcUtil {


//    private static ConcurrentHashMap<String, MySqlJdbcUtil> bJRLPanelConcurrentHashMap = new ConcurrentHashMap();

    public MySqlJdbcUtil(String url, String username, String password) {
//        JdbcUtilV2("com.mysql.jdbc.Driver", "jdbc:mysql://218.201.100.85:3116/xihaian_3.0?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai"
//                , "qdxha", "Runa@2023#");
        JdbcUtilV2("com.mysql.jdbc.Driver", url, username, password);
    }

    public MySqlJdbcUtil(String driver, String url, String username, String password) {
//        JdbcUtilV2("com.mysql.jdbc.Driver", "jdbc:mysql://218.201.100.85:3116/xihaian_3.0?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai"
//                , "qdxha", "Runa@2023#");
        JdbcUtilV2(driver, url, username, password);
    }

//    public static MySqlJdbcUtil getInstance(String dr, String ur, String user, String passwd) {
//        if (bJRLPanelConcurrentHashMap.get(user) != null) return bJRLPanelConcurrentHashMap.get(user);
//        MySqlJdbcUtil mySqlJdbcUtil = new MySqlJdbcUtil(dr, ur, user, passwd);
//        bJRLPanelConcurrentHashMap.put("user",mySqlJdbcUtil);
//        return mySqlJdbcUtil;
//    }

    /**
     * 连接数据库参数
     */
    private String username = "";
    private String password = "";
    private String driver = "";
    private String url = "";
    private Connection connection = null;

    private static Logger logger = LoggerFactory.getLogger(MySqlJdbcUtil.class);

    private void JdbcUtilV2(String dr, String ur, String user, String passwd) {
        try {
            username = user;
            password = passwd;
            driver = dr;
            url = ur;
            Class.forName(driver);
        } catch (Exception e) {
            log.error("连接失败，请检查连接参数 ", e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return 返回Connection
     */
    private Connection getConnection() {
//        Connection connection = null;
//        try {
//            connection = DriverManager.getConnection(url, username, password);
//        } catch (Exception e) {
//            logger.error("getConnection1调试信息，请运维不要管" + ExceptionUtils.getFullStackTrace(e));
//        }

        if (connection == null) {
//            for (int i = 0; i < 4; i++) {
            for (int i = 0; i < 1; i++) {
                try {
                    TimeUnit.SECONDS.sleep(i);
                    connection = DriverManager.getConnection(url, username, password);
                    if (connection != null) {
                        break;
                    }
                } catch (Exception e) {
                    logger.error("getConnection2重试调试信息，请运维不要管" + ExceptionUtils.getFullStackTrace(e));
                }
            }
        }

        return connection;
    }

    /**
     * 查询表
     *
     * @return 返回查询结果的List
     */

    public ArrayList<HashMap<String, Object>> query(String sql, Object... params) {
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);
            setPreparedStatement(preparedStatement, params);
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData(); // key name
            int columnCount = metaData.getColumnCount(); // column count

            ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
            while (resultSet.next()) {
                HashMap<String, Object> rowData = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; ++i) {
                    rowData.put(metaData.getColumnLabel(i), resultSet.getObject(i));
                }
                list.add(rowData);
            }
            return list;
        } catch (Exception e) {
            this.connection=null;
            logger.error("query调试信息，请运维不要管" + sql + "\r\n" + ExceptionUtils.getFullStackTrace(e));
        } finally {
            close(resultSet,preparedStatement,null);
        }
        return new ArrayList<>();
    }


    /**
     * 对sql语句中的占位符进行赋值
     *
     * @param params 参数值
     * @throws SQLException sql异常
     */
    public static void setPreparedStatement(PreparedStatement statement, Object... params) throws SQLException {
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                if ("null".equals(params[i])) {
                    statement.setNull(i + 1, Types.NULL);
                } else {
                    statement.setObject(i + 1, params[i]);
                }
            }
        }
    }

    /**
     * 可处理insert/delete/update语句
     *
     * @param sql    sql语句
     * @param params 占位符参数数组
     * @return 返回bool值，表示是否成功
     */
    public boolean execute(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //获取连接
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //对占位符进行赋值
            setPreparedStatement(preparedStatement, params);
            //提交sql
            preparedStatement.executeUpdate();
            return true;
        } catch (Exception e) {
            
        } finally {
            close(null, preparedStatement, connection);
        }
        return false;
    }


    /**
     * 关闭资源的函数
     */
    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                
            }
            resultSet = null;
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (Exception e) {
                
            }
            preparedStatement = null;
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                
            }
            connection = null;
        }
    }
}
